import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
// 1.装包 yarn add vuex-persistedstate
// 2.引入
// 3.在plugins 中进行配置
// 专门用于vuex数据持久化存储
// 自动将Vuex 中的数据持久化存储至 localStorage
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    // token: localStorage.getItem('token') || ''
    // 默认去localStorage去取
    token: '',
    userInfo: {}
  },
  mutations: {
    updateToken (state, token) {
      state.token = token
      // 同时存入localStorage
      // localStorage.setItem('token', token)
    },
    updateUserInfo (state, userinfo) {
      state.userInfo = userinfo
    }
  },
  actions: {
    // 专门用于vuex中数据异步请求
    async getUserInfo (context) {
      const { data: res } = await axios.get('/my/userinfo', {
        headers: {
          Authorization: context.state.token
        }
      })
      if (res.code === 0) {
        context.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {}
})
